<?php
/**
 * This file belongs to huakaili project
 *
 * @author jszhang
 */

global $logid;
//,$uid,$user;


$pageVars = array();
$errmsg = GetMessageStack();
$userDao = GetUserDAO();

//write to database
if(isset($_POST['action'])) {
	$action=trim($_POST['action']);
	if($action=='change_avatar' && isset( $_FILES["avatar"] ) && 
		!edp_is_empty_string( $_FILES['avatar']['name'] ) )  {
		//use loop to ensure single entrance and single exit
		do{
			$params = array();
			//$params['id'] = intval(trim($_POST['id']));
			$params['id'] = $logid;

			//save file operation
			$userBasicInfo = $userDao->GetUserBasicInfo( $logid);
			$uploader = GetUploder();
			$picinfo = array();
			$uploadinfo = array();
			$params['avatarPath'] = $uploader->SaveUserAvatar( $params['id'], $errmsg, 'change_avatar' );

			$pageVars = array_merge( $pageVars, $params );
			if( $errmsg->size('change_avatar') > 0 )
			{
				break;
			}

			if( !$userDao->UpdateUserAvatarPath( $params ) ) {
				$errmsg->add( 'change_avatar', '写入数据库失败', 'error' );
			}
			else{
				
				// the user may update the head photo in the same day, which
				// makes the new photo has the same name with the old one. So
				// in this situation, we won't delete the old one because the old
				// one has been replaced by the new photo.  --yawei
				
				if( $params['avatarPath'] != $userBasicInfo['logo_path']  &&
						$userBasicInfo['logo_path'] != '' ) {
					@unlink( EdpGetAvatarPath($userBasicInfo['logo_path']));
					$bigPicPath = preg_replace( '/^(.+)s.jpg$/', '\1.jpg', $userBasicInfo['logo_path'] );
					@unlink( EdpGetAvatarPath( $bigPicPath ) );
				}
				
				$errmsg->add( 'crop_avatar', '用鼠标在图片上拖动区域，生成小头像', 'success' );
				
				ob_clean();
				edp_redirect_inner( 'user_setting', 'subpage=crop_avatar');
			}

			break;
		}while(1);
	} else 
		$errmsg->add( 'change_avatar', '未知操作', 'error' );
}
//read from database
//else{
//	$userInfo = getUserFromCookie();
//	if( $userInfo ){
		//get user basic_info from database
		$userBasicInfo = $userDao->GetUserBasicInfo( $logid);
		if( $userBasicInfo ){
			$pageVars['id'] = $userBasicInfo['id'];
			$pageVars['nick'] = $userBasicInfo['nick'];
			if( edp_is_empty_string($userBasicInfo['logo_path']) )
				$pageVars['avatarPath'] = DEFAULT_AVATAR_URL;
			else
				$pageVars['avatarPath'] = EdpGetAvatarUrl( $userBasicInfo['logo_path'] );
		}
		else{
			$errmsg->add( 'change_avatar', '读取用户信息失败', 'error' );
		}
//	}
//	else{
//		$errmsg->add( 'change_avatar', '登录用户信息不合法', 'error' );
//	}
//}
?>
